// AI医疗问答Vue组件
const AIChatComponent = {
  template: `
    <div class="ai-chat-container">
      <div class="ai-chat-header">
        <h2>医疗AI助手</h2>
        <div class="ai-status">{{ connectionStatus }}</div>
      </div>

      <div class="ai-chat-messages" ref="messageContainer">
        <div v-for="(message, index) in messages" :key="index" 
             :class="['ai-message', message.isUser ? 'user-message' : 'ai-response']">
          <div class="message-content" v-html="message.text"></div>
          <div class="message-time">{{ message.time }}</div>
        </div>
      </div>

      <div class="ai-chat-input">
        <input 
          type="text" 
          v-model="userInput" 
          @keyup.enter="sendMessage" 
          :disabled="!isConnected"
          placeholder="请输入您的问题..."
        >
        <button @click="sendMessage" :disabled="!isConnected || userInput.trim() === ''">发送</button>
      </div>
      
      <!-- 调试信息 -->
      <div class="debug-info" style="font-size: 12px; color: #999; margin-top: 10px; padding: 5px; border-top: 1px solid #eee;">
        <div>连接状态: {{ connectionStatus }}</div>
        <div>消息数量: {{ messages.length }}</div>
        <div>最后消息: {{ lastMessageDebug }}</div>
      </div>
    </div>
  `,
  
  data() {
    return {
      userInput: '',
      messages: [],
      socket: null,
      isConnected: false,
      connectionStatus: '正在连接...',
      userId: 'user' + Math.floor(Math.random() * 1000),
      currentStreamingMessage: null,
      lastMessageDebug: '无'
    };
  },
  
  mounted() {
    console.log('AIChatComponent 已挂载');
    this.connectWebSocket();
    // 滚动到底部
    this.$nextTick(() => {
      this.scrollToBottom();
    });
  },
  
  beforeDestroy() {
    // 组件销毁前关闭WebSocket连接
    console.log('AIChatComponent 即将销毁');
    if (this.socket) {
      this.socket.close();
    }
  },
  
  methods: {
    connectWebSocket() {
      // 创建WebSocket连接
      const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
      const host = window.location.hostname + ':8001';
      const wsUrl = `${wsProtocol}//${host}/ws/ai/${this.userId}/`;
      
      console.log('正在连接WebSocket:', wsUrl);
      this.socket = new WebSocket(wsUrl);
      
      // WebSocket事件处理
      this.socket.onopen = this.handleSocketOpen;
      this.socket.onmessage = this.handleSocketMessage;
      this.socket.onclose = this.handleSocketClose;
      this.socket.onerror = this.handleSocketError;
    },
    
    handleSocketOpen(event) {
      console.log('WebSocket连接已建立', event);
      this.isConnected = true;
      this.connectionStatus = '已连接';
    },
    
    handleSocketMessage(event) {
      try {
        console.log('收到WebSocket消息:', event.data);
        const data = JSON.parse(event.data);
        console.log('解析后的消息数据:', data);
        
        // 更新调试信息
        this.lastMessageDebug = `类型:${data.type}, 内容:${data.message ? data.message.substring(0, 20) + '...' : '无'}`;
        
        // 处理不同类型的消息
        if (data.type === 'welcome') {
          console.log('收到欢迎消息');
          this.addMessage(data.message || '欢迎使用医疗AI助手', false);
        } else if (data.type === 'typing') {
          console.log('收到正在输入提示');
          // 可以添加"正在输入"的指示器，或者忽略
        } else if (data.type === 'streaming') {
          console.log('收到流式回答片段:', data.message);
          
          // 处理流式回答
          if (!this.currentStreamingMessage) {
            // 创建一个新的流式回答消息
            console.log('创建新的流式回答消息');
            const now = new Date();
            const timeString = now.toLocaleTimeString();
            
            const newMessage = {
              text: data.message || '',
              isUser: false,
              isStreaming: true,
              time: timeString
            };
            
            this.messages.push(newMessage);
            this.currentStreamingMessage = newMessage;
          } else {
            // 追加到当前流式消息
            console.log('追加到现有回答');
            if (data.message) {
              this.currentStreamingMessage.text += data.message;
            }
          }
          
          // 滚动到底部
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        } else if (data.type === 'complete') {
          console.log('流式回答完成');
          // 流式回答完成
          if (this.currentStreamingMessage) {
            // 标记为非流式
            this.currentStreamingMessage.isStreaming = false;
            this.currentStreamingMessage = null;
          }
        } else if (data.type === 'answer') {
          console.log('收到普通回答');
          this.addMessage(data.message || '无回答内容', false);
        } else if (data.type === 'error') {
          console.log('收到错误消息');
          this.addMessage(data.message || '发生错误', false);
        } else {
          console.log('收到未知类型的消息:', data.type);
        }
      } catch (error) {
        console.error('解析WebSocket消息出错:', error, event.data);
      }
    },
    
    handleSocketClose(event) {
      this.isConnected = false;
      this.connectionStatus = '已断开连接';
      console.log('WebSocket连接已关闭:', event);
      
      // 尝试重新连接
      setTimeout(() => {
        this.connectWebSocket();
      }, 3000);
    },
    
    handleSocketError(error) {
      this.connectionStatus = '连接错误';
      console.error('WebSocket错误:', error);
    },
    
    sendMessage() {
      if (!this.isConnected || this.userInput.trim() === '') {
        console.log('无法发送消息: 未连接或输入为空');
        return;
      }
      
      // 添加用户消息到列表
      this.addMessage(this.userInput, true);
      
      // 发送消息到WebSocket服务器
      const messageData = {
        userid: this.userId,
        mes: this.userInput
      };
      
      console.log('发送消息到服务器:', messageData);
      this.socket.send(JSON.stringify(messageData));
      
      // 清空输入框
      this.userInput = '';
    },
    
    addMessage(text, isUser) {
      if (!text) {
        console.warn('尝试添加空消息');
        text = isUser ? '(空消息)' : '抱歉，我没有回答。';
      }
      
      const now = new Date();
      const timeString = now.toLocaleTimeString();
      
      // 处理换行符
      const formattedText = text.replace(/\n/g, '<br>');
      
      const newMessage = {
        text: formattedText,
        isUser,
        time: timeString
      };
      
      console.log('添加新消息:', newMessage);
      this.messages.push(newMessage);
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    
    scrollToBottom() {
      if (this.$refs.messageContainer) {
        this.$refs.messageContainer.scrollTop = this.$refs.messageContainer.scrollHeight;
      }
    }
  }
};

// 导出组件
if (typeof module !== 'undefined' && module.exports) {
  module.exports = AIChatComponent;
} 